#coding=utf-8
from google.appengine.ext import db
import random

NUM_SHARDS = 20

class CounterShard(db.Model):
  """Shards for the counter"""
  count = db.IntegerProperty(required=True, default=0)   
  name = db.StringProperty(required=True)
  nth = db.IntegerProperty(required=True, default=0)
  
class Counter(object):
  def __init__(self, name):
    '''get or create a count'''
    self.name = name
  
  def get_count(self):
    """Retrieve the value for a given sharded counter."""
    total = 0
    counters = CounterShard.all().filter('name =', self.name).fetch(NUM_SHARDS)
    for counter in counters:
      total += counter.count
    return total
  
  def change_count(self, delta):
    """change the value for a given sharded counter by delta."""
    nth = random.randint(0, NUM_SHARDS - 1)
    counter = CounterShard.all().filter('name =', self.name).filter('nth =', nth).get()
    if counter is None:
      counter = CounterShard(name=self.name, nth=nth)
  
    counter.count += delta
    counter.put()
    '''
    def txn(name):
      nth = random.randint(0, NUM_SHARDS - 1)
      counter = CounterShard.all().filter('name =', name).filter('nth =', nth).get()
      if counter is None:
        counter = CounterShard(name=name, nth=nth)
    
      counter.count += delta
      counter.put()
    
    db.run_in_transaction_custom_retries(10, txn(self.name))
    '''
    
  def remove(self):
    counters = CounterShard.all().filter('name =', self.name).fetch(NUM_SHARDS)
    db.delete(counters)

COUNTER_NAME = 'SENDED'
sended_counter = Counter(COUNTER_NAME)

from google.appengine.ext import webapp
class CounterStatus(webapp.RequestHandler):
  def get(self):
    #name = self.request.get('name')
    c = sended_counter
    self.response.out.write('The count of %s is %i'%(c.name,c.get_count()))
    
